package com.yiwu.common.domain.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.yiwu.common.enums.ResponseCode;
import com.yiwu.common.exception.BusinessException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * @TableName UserFavorites
 */

@EqualsAndHashCode(callSuper = true)
@TableName(value = "UserFavorites")
@Data
@NoArgsConstructor
public class UserFavorites extends Model<UserFavorites> {
    /**
     *
     */
    @TableId
    private Long userId;

    private Long productId;
    /**
     *
     */
    private LocalDateTime createdAt;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;

    public UserFavorites(Long userId, Long productId) {
        this.userId = userId;
        this.productId = productId;
        this.createdAt = LocalDateTime.now();
    }

    public void isValid() {
        if (productId == null) {
            throw new BusinessException(ResponseCode.PRODUCTID_ERROR);
        } else if (userId == null) {
            throw new BusinessException(ResponseCode.SELLER_ERROR);
        }
    }

    public void delete() {
        QueryWrapper<UserFavorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("product_id", productId);
        boolean delete = super.delete(queryWrapper);
        if(!delete) throw new BusinessException(ResponseCode.DEL_FAVORITE_ERROR);
    }

}